import {getRequest} from "./api";

/**
 * @param router
 * @param store
 * initMenu() 里面放两个参数一个是router对象，因为菜单待会格式化好之后要放到router对象里
 * 数据同时还要向store里保存一份，所以要加个store
 */
export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return;
    }
    getRequest("/system/config/menu").then(data => {
        if (data) {
            let fmtRoutes = formatRoutes(data);//把component字符串变成对象
            router.addRoutes(fmtRoutes);
        //     你不能直接调用一个 mutation handler。这个选项更像是事件注册：
        //     “当触发一个类型为 increment 的 mutation 时，调用此函数。”
        //     要唤醒一个 mutation handler，你需要以相应的 type 调用 store.commit 方法：
            store.commit('initRoutes', fmtRoutes);
            //store.dispatch('connect');
        }
    })
}

export const formatRoutes = (routes) => {
    let fmRoutes = []; //最终要返回的数据
    routes.forEach(router => { //routes.forEach  遍历routes
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router; //这里是批量定义变量，其作用等同于let path=router.path
        //let component=router.component ....
        if (children && children instanceof Array) { //判断children存在并且是一个数组
            children = formatRoutes(children);//递归调用
        }
        let fmRouter = {
            path: path, //path:path这个path是上面的path
            name: name,//name:path这个name是上面的name
            iconCls: iconCls,//iconCls:iconCls这个path是上面的iconCls
            meta: meta,//meta:meta这个path是上面的meta
            children: children,//children:children这个children是上面的children
            /**
             * @param resolve
             * 把component当做一个方法来处理，里面有个参数叫resolve
             * 这里是动态导入
             */
            component(resolve) {
                if (component.startsWith("Home")) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith("Emp")) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith("Per")) {
                    require(['../views/per/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sal")) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sta")) {
                    require(['../views/sta/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sys")) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
       // console.log(children);
        fmRoutes.push(fmRouter);
    })
    //console.log(children);
    return fmRoutes;
}